#include "TonyCaptureScreenTestWindow.h"
#include "TonyCaptureScreen.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>


TonyCaptureScreenTestWindow::TonyCaptureScreenTestWindow(QWidget* parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	this->setWindowTitle("directx屏幕抓取测试");
	setAttribute(Qt::WA_DeleteOnClose, true);  // 关闭时自动销毁窗口
}

void TonyCaptureScreenTestWindow::choiceOutputPath()
{
	QString mPath = QFileDialog::getSaveFileName(nullptr, "请选择输出文件地址", "");
	ui.outputEdit->setText(mPath);
}
void TonyCaptureScreenTestWindow::startCaptureScreen()
{
	isClickedRecord = true;
	QString filePath = ui.outputEdit->text();
	if (filePath.isEmpty()) {
		QMessageBox::warning(this, "温馨提示", "输入、输出文件的路径不能为空");
		return;
	}
	writer = BinaryFileWriter::Create();
	writer->Init(filePath.toStdString());
	TonyCaptureScreen::Get()->outFilePath = filePath;
	TonyCaptureScreen::Get()->Start();
	// 创建并启动后台线程
	renderThread = std::make_unique<std::thread>(&TonyCaptureScreenTestWindow::Save, this);
	
}

void TonyCaptureScreenTestWindow::stopCaptureScreen()
{
	if (isClickedRecord) {
		TonyCaptureScreen::Get()->Stop();
		isSaveing = false;
		if (renderThread) {
			renderThread->join();
		}
		if (writer) {
			writer->Close();
			writer = nullptr;
		}
	}
}

void TonyCaptureScreenTestWindow::Save()
{
	int count = 0;
	while (isSaveing)
	{
		std::list<char*> mList = TonyCaptureScreen::Get()->getScreenDataList();
		if (!mList.empty())
		{
			char* data = mList.front();
			writer->Write(data, TonyCaptureScreen::Get()->getLinesize());
			mList.pop_front();
			qDebug() << "正在保存数据->";
		}
	}
	qDebug() << "数据保存结束";

}

void TonyCaptureScreenTestWindow::closeEvent(QCloseEvent* event) {
	event->accept();  // 接受关闭事件（允许关闭）

	if (isClickedRecord) {
		TonyCaptureScreen::Get()->Stop();
		isSaveing = false;
		if (renderThread && renderThread->joinable()) {
			renderThread->join();
		}
		if (writer) {
			writer->Close();
			writer = nullptr;
		}

	}
	qDebug() << "窗口已关闭";
}

TonyCaptureScreenTestWindow::~TonyCaptureScreenTestWindow()
{
}
